/**
 * pending [待定]初始状态
 * resolved [实现]操作成功
 * rejected [被否决]操作失败
 * 当promise状态发生改变，就会触发then()里的响应函数处理后续步骤
 * promise状态一经改变，不会再变。
 * 
 * Promise.all() 批量执行
 * Promise.all([p1, p2, p3])用于将多个promise实例，包装成一个新的Promise实例，返回的实例就是普通的promise
 * 它接收一个数组作为参数
 * 数组里可以是Promise对象，也可以是别的值，只有Promise会等待状态改变
 * 当所有的子Promise都完成，该Promise完成，返回值是全部值得数组
 * 有任何一个失败，该Promise失败，返回值是第一个失败的子Promise结果
 * 有任何一个失败，该Promise失败，返回值是第一个失败的子Promise结果
 */
const RESOLVE = 'resolved';
const REJECT = 'rejected'
const PENDING = 'pending'

class MyPromise {
  status = PENDING;
  result = undefined;
  reason = undefined;
  reSolveArr = [];
  reJectArr = [];
  constructor (excution) {
    const resolve = (result)=>{
      if(this.status === PENDING){
        this.result = result;
        this.status = RESOLVE;
        this.reSolveArr.map(fn=>fn())
      }
    }
    const reject = (reason)=>{
      if(this.status === PENDING){
        this.reason = reason;
        this.status = REJECT;
        this.reJectArr.map(fn=>fn())
      }
    }
    excution(resolve, reject)
  }
  then(onResolved, onRejected){
    if(this.status === RESOLVE){
      setTimeout(() => {
        onResolved(this.result)
      }, 0);
    }
    if(this.status === REJECT){
      setTimeout(() => {
        onRejected(this.reason)
      }, 0);
    }
    if(this.status === PENDING){
      this.reSolveArr.push(()=>{
        onResolved(this.result)
      })
      this.reJectArr.push(()=>{
        onRejected(this.reason)
      })
    }
  }
}

const p = new MyPromise((resolve, reject)=>{
  // resolve('我好帅！！')
  setTimeout(() => {
    resolve('我好帅！！')
  }, 2000);
  // reject('err')
})

p.then((res)=>{
  console.log(res)
},(err)=>{
  console.log(err)
})

var xhr = new XMLHttpRequest()
xhr.open('GET','https://m.manhuayang.com/api/getsortlist/?page=5&comic_sort=&size=48')
xhr.responseType = 'json'
xhr.send()
xhr.onreadystatechange = ()=>{
  if(xhr.readyState == 4){
    if(xhr.status >= 200 && xhr.status <= 300){
      console.log(xhr.response)
    }else{
      console.log(xhr.status)
    }
  }
}
